package com.songshuai.sales.tool.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.songshuai.sales.tool.dto.po.AllRoleDto;
import com.songshuai.sales.tool.dto.response.login.LoginUserResDto;
import com.songshuai.webapi.common.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yubo on 12/18/2018.
 */
@Slf4j
public class BaseServiceImpl {

    @Autowired
    protected RedisUtil redisUtil;

    @Autowired
    private HttpServletRequest request;

    /**
     * 获取当前登录用户（使用时记得判空）
     * @return
     */
    protected LoginUserResDto getCurrentUser() {

        try {
            String loginUser = (String) request.getAttribute("loginUser");
            JSONObject jsonObject = JSON.parseObject(loginUser);

            LoginUserResDto loginUserResDto = new LoginUserResDto();
            loginUserResDto.setUserId(jsonObject.getString("UserId"));
            loginUserResDto.setTrueName(jsonObject.getString("TrueName"));
            loginUserResDto.setEmail(jsonObject.getString("Email"));
            loginUserResDto.setSex(jsonObject.getString("Sex"));
            loginUserResDto.setMobile(jsonObject.getString("Mobile"));
            loginUserResDto.setWorkNo(jsonObject.getString("WorkNo"));
            loginUserResDto.setUserName(jsonObject.getString("UserName"));
            loginUserResDto.setMainRole(jsonObject.getString("MainRole"));
            loginUserResDto.setMinorRole(StringUtils.hasText(jsonObject.getString("MinorRole")) ? jsonObject.getString("MinorRole") : "");
            JSONArray roles = jsonObject.getJSONArray("SysRoles");
            List<AllRoleDto> allRoleDtos=new ArrayList<>();
            if(roles.size()>0){
                allRoleDtos= JSONObject.parseArray(roles.toJSONString(), AllRoleDto.class);
            }
            loginUserResDto.setAllRole(allRoleDtos);
            return loginUserResDto;

        }catch (Exception e){
            return null;
        }

    }


}
